package com.sunxu.exercise2;

import java.util.HashMap;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author Sun
 * @create 2017-07-31-23:21
 */
public class DefaultController implements Controller {
    private Map requestHandlers = new HashMap();

    protected RequestHandler getHandler(Request request) {
        if (!this.requestHandlers.containsKey(request.getName())) {
            String message = "Cannot find handler for request name " + "[" + request.getName() + "]";

            throw new RuntimeException(message);
        }
        return (RequestHandler) this.requestHandlers.get(request.getName());
    }

    @Override
    public Response processRequest(Request request) {
        Response response;
        try {
            response = getHandler(request).process(request);
        } catch (Exception e) {
            response = new ErrorResponse(request, e);
        }
        return response;
    }

    @Override
    public void addHandler(Request request, RequestHandler requestHandler) {
        if (this.requestHandlers.containsKey(request.getName())) {
            String message = "A request handler has " + "already been registered for request name " + "[" + request.getName() + "]";
            throw new RuntimeException(message);
        } else {
            this.requestHandlers.put(request.getName(), requestHandler);
        }
    }





    public class SampleResponse implements Response {
    }



}
